<template>
  <div class="gif-editor-page">
    <div class="editor-container">
      <h1>GIF编辑</h1>
      
      <el-upload
        class="upload-area"
        action="#"
        :auto-upload="false"
        :on-change="handleFileChange"
        accept=".gif"
      >
        <div class="upload-content">
          <el-icon class="upload-icon"><Upload /></el-icon>
          <div class="upload-text">点击上传GIF文件</div>
        </div>
      </el-upload>

      <div v-if="frames.length" class="editor-content">
        <div class="speed-control">
          <span class="speed-label">播放速度：</span>
          <el-slider 
            v-model="speed" 
            :min="0.1" 
            :max="2" 
            :step="0.1" 
            :format-tooltip="formatSpeed"
          />
        </div>

        <div class="frames-container">
          <div 
            v-for="(frame, index) in frames" 
            :key="index"
            class="frame"
            draggable="true"
            @dragstart="dragStart(index)"
            @dragover.prevent
            @dragenter.prevent
            @drop="drop(index)"
          >
            <img :src="frame.url" :alt="`Frame ${index + 1}`">
            <div class="frame-actions">
              <el-button 
                type="danger" 
                circle 
                size="small" 
                @click="deleteFrame(index)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <div class="frame-number">{{ index + 1 }}</div>
          </div>
        </div>

        <el-upload
          class="add-frame"
          action="#"
          :auto-upload="false"
          :on-change="addNewFrame"
          accept="image/*"
        >
          <el-button type="primary">
            <el-icon><Plus /></el-icon>
            添加新帧
          </el-button>
        </el-upload>
      </div>

      <div class="preview-area" v-if="editedGifUrl">
        <h3>预览：</h3>
        <img :src="editedGifUrl" alt="Edited GIF" class="preview-gif">
      </div>

      <div class="button-group">
        <el-button 
          type="primary" 
          @click="editGif" 
          :disabled="!frames.length"
          :loading="isEditing"
        >
          <el-icon><VideoPlay /></el-icon>
          生成GIF
        </el-button>
        <el-button 
          type="success" 
          @click="downloadGif" 
          :disabled="!editedGifUrl"
        >
          <el-icon><Download /></el-icon>
          下载GIF
        </el-button>
        <el-button @click="clearAll" v-if="frames.length">
          <el-icon><Delete /></el-icon>
          清空
        </el-button>
        <el-button type="warning" @click="goToHomepage">
          <el-icon><Back /></el-icon>
          返回
        </el-button>
      </div>

      <div class="notes">
        <h3>帮助说明：</h3>
        <ul>
          <li>支持上传GIF文件进行编辑</li>
          <li>可以调整GIF播放速度</li>
          <li>支持帧的添加、删除和拖拽排序</li>
          <li>可以添加新的图片作为帧</li>
          <li>编辑完成后可预览和下载</li>
          <li>建议GIF文件大小不超过10MB</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Upload, Delete, Plus, VideoPlay, Download, Back } from '@element-plus/icons-vue'
import GIF from 'gif.js'
import { GifReader } from 'omggif'

const router = useRouter()
const frames = ref([])
const editedGifUrl = ref('')
const speed = ref(1)
const isEditing = ref(false)
let draggedItem = null

const handleFileChange = async (file) => {
  if (file.raw.size > 10 * 1024 * 1024) {
    ElMessage.warning('文件大小不能超过10MB')
    return
  }

  const reader = new FileReader()
  reader.onload = function(e) {
    try {
      const buffer = e.target.result
      const gif = new GifReader(new Uint8Array(buffer))
      const frameCount = gif.numFrames()
      frames.value = []
      
      for (let i = 0; i < frameCount; i++) {
        const frameInfo = gif.frameInfo(i)
        const imageData = new ImageData(frameInfo.width, frameInfo.height)
        gif.decodeAndBlitFrameRGBA(i, imageData.data)
        
        const canvas = document.createElement('canvas')
        canvas.width = frameInfo.width
        canvas.height = frameInfo.height
        const ctx = canvas.getContext('2d')
        ctx.putImageData(imageData, 0, 0)
        
        frames.value.push({
          url: canvas.toDataURL(),
          delay: frameInfo.delay * 10
        })
      }
      ElMessage.success('GIF文件加载成功')
    } catch (error) {
      ElMessage.error('GIF文件解析失败')
      console.error('GIF parsing error:', error)
    }
  }
  reader.readAsArrayBuffer(file.raw)
}

const formatSpeed = (value) => {
  return `${value}x`
}

const deleteFrame = (index) => {
  frames.value.splice(index, 1)
  ElMessage.success('帧已删除')
}

const addNewFrame = (file) => {
  if (!file.raw.type.startsWith('image/')) {
    ElMessage.error('请上传图片文件')
    return
  }

  const reader = new FileReader()
  reader.onload = (e) => {
    frames.value.push({
      url: e.target.result,
      delay: 100
    })
    ElMessage.success('新帧已添加')
  }
  reader.readAsDataURL(file.raw)
}

const dragStart = (index) => {
  draggedItem = frames.value[index]
  event.target.classList.add('dragging')
}

const drop = (index) => {
  event.target.classList.remove('dragging')
  const draggedOverItem = frames.value[index]
  const tempFrames = [...frames.value]
  const draggedItemIndex = tempFrames.indexOf(draggedItem)
  tempFrames[draggedItemIndex] = draggedOverItem
  tempFrames[index] = draggedItem
  frames.value = tempFrames
}

const editGif = () => {
  if (frames.value.length === 0) {
    ElMessage.warning('请先添加帧')
    return
  }

  isEditing.value = true
  ElMessage.info('正在生成GIF，请稍候...')

  const gif = new GIF({
    workers: 2,
    quality: 10,
    workerScript: '/gif.worker.js'
  })

  let loadedFrames = 0
  frames.value.forEach(frame => {
    const img = new Image()
    img.onload = () => {
      gif.addFrame(img, { delay: frame.delay / speed.value })
      loadedFrames++
      if (loadedFrames === frames.value.length) {
        gif.render()
      }
    }
    img.src = frame.url
  })

  gif.on('finished', blob => {
    editedGifUrl.value = URL.createObjectURL(blob)
    isEditing.value = false
    ElMessage.success('GIF生成成功')
  })
}

const downloadGif = () => {
  if (!editedGifUrl.value) return

  const link = document.createElement('a')
  link.href = editedGifUrl.value
  link.download = `edited_${new Date().getTime()}.gif`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('下载开始')
}

const clearAll = () => {
  frames.value = []
  editedGifUrl.value = ''
  speed.value = 1
  ElMessage.success('已清空')
}

const goToHomepage = () => {
  router.push('/')
}
</script>

<style lang="scss" scoped>
.gif-editor-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  overflow-y: auto;

  .editor-container {
    max-width: 1000px;
    width: 96%;
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
    padding: 30px;
    box-sizing: border-box;
    margin: 10px auto;

    h1 {
      text-align: center;
      color: #4a5568;
      font-size: 28px;
      margin-bottom: 30px;
      text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
    }

    .upload-area {
      border: 2px dashed #dcdfe6;
      border-radius: 12px;
      padding: 30px;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        border-color: #409EFF;
        background-color: rgba(64, 158, 255, 0.05);
      }

      .upload-content {
        .upload-icon {
          font-size: 48px;
          color: #8c939d;
          margin-bottom: 10px;
        }

        .upload-text {
          color: #606266;
          font-size: 14px;
        }
      }
    }

    .editor-content {
      margin-top: 30px;

      .speed-control {
        display: flex;
        align-items: center;
        gap: 15px;
        margin-bottom: 20px;

        .speed-label {
          color: #606266;
          font-size: 14px;
          min-width: 70px;
        }

        .el-slider {
          flex: 1;
        }
      }

      .frames-container {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        margin-bottom: 20px;
        min-height: 120px;
        padding: 10px;
        background-color: #f8fafc;
        border-radius: 8px;

        .frame {
          position: relative;
          width: 100px;
          height: 100px;
          border: 2px solid #dcdfe6;
          border-radius: 8px;
          overflow: hidden;
          cursor: move;
          transition: all 0.3s ease;

          &:hover {
            border-color: #409EFF;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

            .frame-actions {
              opacity: 1;
            }
          }

          &.dragging {
            opacity: 0.5;
          }

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .frame-actions {
            position: absolute;
            top: 5px;
            right: 5px;
            opacity: 0;
            transition: opacity 0.3s ease;
          }

          .frame-number {
            position: absolute;
            bottom: 5px;
            left: 5px;
            background-color: rgba(0, 0, 0, 0.6);
            color: white;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 12px;
          }
        }
      }

      .add-frame {
        text-align: center;
        margin-top: 20px;
      }
    }

    .preview-area {
      margin-top: 30px;
      text-align: center;

      h3 {
        color: #4a5568;
        margin-bottom: 15px;
      }

      .preview-gif {
        max-width: 100%;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
    }

    .button-group {
      display: flex;
      gap: 15px;
      justify-content: center;
      margin: 30px 0;

      .el-button {
        min-width: 120px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 12px 20px;
        font-size: 14px;
        border-radius: 8px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .el-icon {
          font-size: 16px;
        }
      }
    }

    .notes {
      margin-top: 40px;
      padding: 20px;
      background-color: #f0f5ff;
      border-radius: 12px;
      color: #606266;
      text-align: left;

      h3 {
        color: #409EFF;
        margin: 0 0 15px 0;
        font-size: 16px;
        text-align: left;
      }

      ul {
        margin: 0;
        padding-left: 0;
        list-style-type: none;
        text-align: left;

        li {
          margin-bottom: 12px;
          line-height: 1.6;
          position: relative;
          padding-left: 18px;
          text-align: left;

          &:before {
            content: "•";
            color: #409EFF;
            font-size: 18px;
            position: absolute;
            left: 0;
            top: -2px;
          }

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .gif-editor-page {
    padding: 10px;

    .editor-container {
      padding: 20px;
      width: 100%;

      h1 {
        font-size: 24px;
        margin-bottom: 20px;
      }

      .upload-area {
        padding: 20px;

        .upload-content {
          .upload-icon {
            font-size: 36px;
          }
        }
      }

      .editor-content {
        .speed-control {
          flex-direction: column;
          align-items: stretch;
          gap: 10px;

          .speed-label {
            text-align: left;
          }
        }

        .frames-container {
          justify-content: center;
        }
      }

      .button-group {
        flex-direction: column;
        gap: 10px;

        .el-button {
          width: 100%;
          margin: 0;
        }
      }

      .notes {
        padding: 15px;
        margin-top: 30px;

        h3 {
          font-size: 15px;
        }

        ul li {
          font-size: 13px;
          margin-bottom: 8px;
        }
      }
    }
  }
}
</style>
